package work.comeback.omo.controller.servlet.home;

import jakarta.servlet.ServletConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import work.comeback.omo.dao.movie.IMovieDetail;
import work.comeback.omo.dao.movie.IMovieInfo;
import work.comeback.omo.model.movie.display.MovieCard;
import work.comeback.omo.model.movie.info.MovieVoidData;
import work.comeback.omo.service.MovieService;
import work.comeback.omo.service.imp.MovieServiceImpl;

import java.io.IOException;
import java.io.Serial;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet(displayName = "HomePageServlet", urlPatterns = {"/home", "/index", "/index.jsp"})
public class HomePageServlet extends HttpServlet {
    private static final Logger logger = LoggerFactory.getLogger(HomePageServlet.class);

    @Serial
    private static final long serialVersionUID = 1L;
    private final MovieService movieService = new MovieServiceImpl();
    private final IMovieInfo movieInfoService = movieService.getMovieInfo();
    private final IMovieDetail movieDetailService = movieService.getMovieDetail();

    private final HashMap<String, ArrayList<MovieCard>> movieCardsMap = new HashMap<>();

    @Override
    public void init(ServletConfig config) {
        if (movieCardsMap.isEmpty()){
            logger.info("first request, setup with data....");
            this.createHomeData();
        }
    }

    private void forwardBefore(HttpServletRequest request, HttpServletResponse response) {
        request.setAttribute("movieCardsMap", movieCardsMap);
    }

    private void createHomeData() {
        Map<String, List<MovieVoidData>> groupedDataByTypeName = movieInfoService.getGroupedDataByTypeName(-1);

        groupedDataByTypeName.forEach((tagName, vData) -> {
            if (vData.size() >= 6) {
                ArrayList<MovieCard> aCards = new ArrayList<>();
                vData.forEach(movieData -> {
                    if (aCards.size() != 12) {
                        MovieCard card = new MovieCard(movieData, movieDetailService);
                        if (!card.isNull()) {
                            aCards.add(card);
                        }
                    }
                });
                movieCardsMap.put(tagName, aCards);
            }
        });
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 转发前处理逻辑
        this.forwardBefore(request, response);

        // 转发到首页
        request.getRequestDispatcher("/WEB-INF/views/index.jsp").forward(request, response);
    }
}
